package cn.wonderland.search.service.impl;

import cn.wonderland.base.util.*;
import cn.wonderland.order.domain.OrderPetAcquisition;
import cn.wonderland.order.dto.AcceptDto;
import cn.wonderland.order.mapper.OrderPetAcquisitionMapper;
import cn.wonderland.org.domain.Shop;
import cn.wonderland.org.mapper.ShopMapper;
import cn.wonderland.pet.domain.Pet;
import cn.wonderland.pet.mapper.PetMapper;
import cn.wonderland.search.domain.SearchMasterMsg;
import cn.wonderland.search.domain.SearchMasterMsgAuditLog;
import cn.wonderland.search.dto.SearchMasterMsgDto;
import cn.wonderland.search.mapper.SearchMasterMsgAuditLogMapper;
import cn.wonderland.search.mapper.SearchMasterMsgMapper;
import cn.wonderland.search.service.ISearchMasterMsgService;
import cn.wonderland.base.service.impl.BaseServiceImpl;
import cn.wonderland.user.domain.Logininfo;
import cn.wonderland.user.domain.User;
import cn.wonderland.user.mapper.LogininfoMapper;
import cn.wonderland.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wonderland
 * @since 2023-01-10
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper auditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderMapper;


    /**
     * 宠物寻主
     * @param dto
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsgDto dto) {
        // 参数校验
        // 1.保存数据
        SearchMasterMsg masterMsg = new SearchMasterMsg();
        BeanUtils.copyProperties(dto, masterMsg);
        // 设置状态
        masterMsg.setState(0);
        // 2.设置userId
        // 2.1 获取logininfo
        Logininfo logininfo = LoginContext.getUserInfo().getLogininfo();
        // 2.2 通过logininfoId获取用户id
        User user= userMapper.findByLogininfoId(logininfo.getId());
        masterMsg.setUserId(user.getId());
        // 3.保存数据
        super.add(masterMsg);
        // 4.百度AI审核
        if(!BaiduAuditUtils.TextCensor(masterMsg.getName())){
            // 审核不通过，设置审核表格状态
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setMsgId(masterMsg.getId());
            auditLog.setState(0);
            auditLog.setAuditId(-1L);
            auditLog.setAuditTime(new Date());
            auditLog.setNote("宠物名审核不通过！");
            // 添加审核日志
            auditLogMapper.add(auditLog);
            // SearchMasterMsg状态设置成审核失败= 2
            masterMsg.setState(2);
        } else { // 审核成功
            // 调用工具类寻找店铺
            Point point = DistanceUtil.getPoint(masterMsg.getAddress());
            List<Shop> shopList = shopMapper.findAll();
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopList);
            if(nearestShop != null){ // 找到了店铺
                masterMsg.setShopId(nearestShop.getId()); // 设置店铺id
            }
            // 修改审核状态为审核通过= 1
            masterMsg.setState(1);
        }
        // 修改店铺状态
        super.update(masterMsg);
        return AjaxResult.me().success();
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        // 把当前消息 的shopId改成null
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void accept(AcceptDto dto) {
        // 参数校验

        // 1.根据msgId查询数据
        SearchMasterMsg msg = searchMasterMsgMapper.findById(dto.getMsgId());
        // 2.生成收购单信息
        OrderPetAcquisition order = getOrder(dto, msg);
        // 3.生成宠物信息
        Pet pet = getPet(msg);
        // 4.修改msg的状态为 已接单
        msg.setState(3);
        searchMasterMsgMapper.update(msg);
        // 5.添加宠物信息
        petMapper.add(pet);
        // 6.添加order
        order.setPetId(pet.getId());
        orderMapper.add(order);


    }

    public Pet getPet(SearchMasterMsg msg){
        return Pet
                .builder()
                .name(msg.getName())
                .costprice(BigDecimal.valueOf(msg.getPrice()))
                .state(0)
                .typeId(msg.getPetType())
                .createtime(new Date())
                .shopId(msg.getShopId())
                .searchMasterMsgId(msg.getId())
                .build();
    }

    public OrderPetAcquisition getOrder(AcceptDto dto,SearchMasterMsg msg) {
        return OrderPetAcquisition.builder()
                .orderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()))
                .digest(dto.getNote())
                .lastConfirmTime(new Date(System.currentTimeMillis()+2*24*60*60*1000))
                .state(0)
                .price(BigDecimal.valueOf(msg.getPrice()))
                .payType(1)
                .paySn("123456")
                .userId(msg.getUserId())
                .shopId(msg.getShopId())
                .address(msg.getAddress())
                .empId(dto.getHandler())
                .msgId(msg.getId())
                .build();
    }
}
